const connection = require("../app/database");

class commentService {
	// 发表评论
	async create(user_id, moment_id, content) {
		const statement = `INSERT INTO comment (user_id, moment_id, content) VALUES(?,?,?);`;
		const [result] = await connection.execute(statement, [
			user_id,
			moment_id,
			content
		]);

		// 返回结果
		return result;
	}

	// 回复评论
	async reply(user_id, moment_id, comment_id, content) {
		const statement = `INSERT INTO comment (user_id, moment_id, comment_id, content) VALUES(?,?,?,?);`;
		const [result] = await connection.execute(statement, [
			user_id,
			moment_id,
			comment_id,
			content
		]);

		// 返回结果
		return result;
	}

	// 修改评论
	async update(comment_id, content) {
		const statement = `UPDATE comment SET content = ? WHERE id = ?;`;
		const [result] = await connection.execute(statement, [
			content,
			comment_id
		]);

		// 返回结果
		return result;
	}

	// 删除评论
	async remove(commentId) {
		const statement = `DELETE FROM comment WHERE id = ?;`;
		const [result] = await connection.execute(statement, [commentId]);

		// 返回数据
		return result;
	}

	// （独立接口）获取评论（评论，评论人）
	async getCommentById(momentId) {
		const statement = `SELECT 
                        c.id, c.content, c.comment_id, c.createAt createTime, c.updateAt updateTime,
                        JSON_OBJECT("id", u.id, "name", u.name) user
                       FROM comment c
                       LEFT JOIN user u ON u.id = c.user_id
                       WHERE moment_id = ?;`;
		const [result] = await connection.execute(statement, [momentId]);

		// 返回数据
		return result;
	}
}

module.exports = new commentService();
